import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/common/ProfileDTO.dart';
import 'package:ichinesereader/models/common/ProfileResult.dart';
import 'package:ichinesereader/models/common/Settings.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/widgets/dialogs/changeUserPasswordReactive.dart';
import 'package:ichinesereader/widgets/forms/buttonGroup.dart';
import 'package:ichinesereader/widgets/forms/textField.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/themes/buttonStyles.dart';
import 'package:universal_html/html.dart' as uHtml;
import '../../controller/user.dart';

class ProfileWidget extends StatelessWidget {
  ProfileWidget({Key? key, required this.profile}) : super(key: key);

  final ProfileResult profile;
  final GlobalKey<FormBuilderState> _formKeyProfileWidget =
      GlobalKey<FormBuilderState>();
  final AppButtonStyles _appButtonStyles = new AppButtonStyles();

  @override
  Widget build(BuildContext context) {
    final box = Hive.box('appconfig');
    final UserController _usercontroller = Get.find();
    bool isIndividual = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Individual;
    bool isParent = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Parent;

    final PageStyles _pageStyles = PageStyles();
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;

    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12.0),
        padding: EdgeInsets.all(21.0),
        decoration: _pageStyles.dataGridForground(),
        child: Column(
          children: [
            FormBuilder(
              key: _formKeyProfileWidget,
              child: Column(
                children: <Widget>[
                  TextFieldWidget(
                    name: "userName",
                    label: "Username".tr,
                    readOnly: true,
                    initialValue: profile.userName,
                  ),
                  TextFieldWidget(
                    name: "firstName",
                    label: "First Name".tr,
                    initialValue: profile.firstName,
                    required: true,
                  ),
                  TextFieldWidget(
                    name: "lastName",
                    label: "Last Name".tr,
                    initialValue: profile.lastName,
                    required: true,
                  ),
                  TextFieldWidget(
                    name: "email",
                    label: 'Email'.tr,
                    initialValue: profile.email,
                    //required: true,
                  ),
                  if (!isParent)
                    ButtonGroupWidget(
                        name: "lang",
                        label: "Audio".tr,
                        options: Constants.audioOptions,
                        initialValue:
                            profile.settings?.lang ?? Constants.Mandarin),
                  if (!isParent)
                    ButtonGroupWidget(
                        name: "language",
                        label: "Text".tr,
                        options: Constants.textOptions,
                        initialValue:
                            profile.settings?.language ?? Constants.Simplified),
                  if (!isParent)
                    FormBuilderSwitch(
                      name: "pinyin",
                      title: Text(
                        "Pinyin".tr,
                        style: TextStyle(fontSize: 18.0),
                      ),
                      initialValue: profile.settings?.pinyin ?? true,
                    ),
                  isSmallScreen
                      ? Column(
                          children: [
                            isIndividual
                                ? ElevatedButton(
                                    child: Text('Subscribe'.tr),
                                    onPressed: () {
                                      if (GetPlatform.isWeb)
                                        launchInWebViewWithJavaScript(
                                            '${Constants.BaseURL}icr/student/individual/subscription');
                                      else
                                        Get.toNamed('/individual/subscription');
                                    },
                                  )
                                : Text(''),
                            isIndividual
                                ? SizedBox(
                                    width: 15,
                                  )
                                : Text(''),
                            Container(
                              margin: EdgeInsets.only(bottom: 9.0),
                              width: double.infinity,
                              height: 60.0,
                              child: ElevatedButton(
                                style: _appButtonStyles.exportButtonStyle(),
                                child: Text(
                                  'Change Password'.tr,
                                  style: TextStyle(
                                    fontSize: 15.0,
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : Get.theme.primaryColorLight,
                                  ),
                                ),
                                onPressed: () {
                                  showGeneralDialog(
                                      context: context,
                                      transitionDuration:
                                          Duration(milliseconds: 400),
                                      pageBuilder: (bc, ania, anis) {
                                        //return ChangeUserPasswordDialog();
                                        return ChangeUserPasswordReactiveDialog(
                                            isTeacherOrSchooladmin:
                                                isIndividual == false);
                                      });
                                },
                              ),
                            ),
                            Container(
                              width: double.infinity,
                              height: 60.0,
                              child: ElevatedButton(
                                style: _appButtonStyles.exportButtonStyle(),
                                child: Text(
                                  'Submit'.tr,
                                  style: TextStyle(
                                    fontSize: 15.0,
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : Get.theme.primaryColorLight,
                                  ),
                                ),
                                onPressed: () {
                                  _formKeyProfileWidget.currentState?.save();
                                  if (_formKeyProfileWidget.currentState!
                                      .validate()) {
                                    var updatedValue = _formKeyProfileWidget
                                        .currentState?.value;
                                    ProfileDTO newProfile = new ProfileDTO(
                                        firstName: updatedValue?["firstName"],
                                        lastName: updatedValue?["lastName"],
                                        email: updatedValue?["email"],
                                        settings: new Settings(
                                            lang: updatedValue?["lang"],
                                            language: updatedValue?["language"],
                                            pinyin: updatedValue?["pinyin"]));

                                    _usercontroller
                                        .updateProfile(newProfile)
                                        .then((statusResult) {
                                      if (statusResult.status == 1000) {
                                        if (!isParent) {
                                          _usercontroller.setLanguage(
                                              newProfile.settings?.language);
                                          _usercontroller.setLang(
                                              newProfile.settings?.lang);
                                          _usercontroller.setPinyin(
                                              newProfile.settings?.pinyin);
                                          if (GetPlatform.isWeb) {
                                            uHtml.window.localStorage['lang'] =
                                                '${newProfile.settings?.lang ?? 'Mandarin'}';
                                            uHtml.window
                                                    .localStorage['language'] =
                                                '${newProfile.settings?.language ?? 'Simplified'}';
                                          }
                                        }

                                        showSnackMsg(
                                            'Profile successfully updated');
                                      } else {
                                        showSnackMsg('Error to update profile');
                                      }
                                    });
                                  }
                                },
                              ),
                            ),
                          ],
                        )
                      : Padding(
                          padding: const EdgeInsets.only(top: 30.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              isIndividual
                                  ? ElevatedButton(
                                      child: Text('Subscribe'.tr),
                                      onPressed: () {
                                        if (GetPlatform.isWeb)
                                          launchInWebViewWithJavaScript(
                                              '${Constants.BaseURL}icr/student/individual/subscription');
                                        else
                                          Get.toNamed(
                                              '/individual/subscription');
                                      },
                                    )
                                  : Text(''),
                              isIndividual
                                  ? SizedBox(
                                      width: 15,
                                    )
                                  : Text(''),
                              Container(
                                width: 210.0,
                                height: 45.0,
                                child: ElevatedButton(
                                  style: _appButtonStyles.profileButtonStyle(),
                                  child: Text(
                                    'Change Password'.tr,
                                    style: TextStyle(
                                      fontSize: 15.0,
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Get.theme.primaryColorLight,
                                    ),
                                  ),
                                  onPressed: () {
                                    showGeneralDialog(
                                        context: context,
                                        transitionDuration:
                                            Duration(milliseconds: 400),
                                        pageBuilder: (bc, ania, anis) {
                                          //return ChangeUserPasswordDialog();
                                          return ChangeUserPasswordReactiveDialog(
                                              isTeacherOrSchooladmin:
                                                  isIndividual == false);
                                        });
                                  },
                                ),
                              ),
                              SizedBox(
                                width: 12.0,
                              ),
                              Container(
                                width: 210.0,
                                height: 45.0,
                                child: ElevatedButton(
                                  style: _appButtonStyles.profileButtonStyle(),
                                  child: Text(
                                    'Submit'.tr,
                                    style: TextStyle(
                                      fontSize: 15.0,
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Get.theme.primaryColorLight,
                                    ),
                                  ),
                                  onPressed: () {
                                    _formKeyProfileWidget.currentState?.save();
                                    if (_formKeyProfileWidget.currentState!
                                        .validate()) {
                                      var updatedValue = _formKeyProfileWidget
                                          .currentState?.value;
                                      ProfileDTO newProfile = new ProfileDTO(
                                          firstName: updatedValue?["firstName"],
                                          lastName: updatedValue?["lastName"],
                                          email: updatedValue?["email"],
                                          settings: new Settings(
                                              lang: updatedValue?["lang"],
                                              language:
                                                  updatedValue?["language"],
                                              pinyin: updatedValue?["pinyin"]));

                                      _usercontroller
                                          .updateProfile(newProfile)
                                          .then((statusResult) {
                                        if (statusResult.status == 1000) {
                                          if (!isParent) {
                                            _usercontroller.setLanguage(
                                                newProfile.settings?.language);
                                            _usercontroller.setLang(
                                                newProfile.settings?.lang);
                                            _usercontroller.setPinyin(
                                                newProfile.settings?.pinyin);
                                            if (GetPlatform.isWeb) {
                                              uHtml.window
                                                      .localStorage['lang'] =
                                                  '${newProfile.settings?.lang ?? 'Mandarin'}';
                                              uHtml.window.localStorage[
                                                      'language'] =
                                                  '${newProfile.settings?.language ?? 'Simplified'}';
                                            }
                                          }

                                          showSnackMsg(
                                              'Profile successfully updated');
                                        } else {
                                          showSnackMsg(
                                              'Error to update profile');
                                        }
                                      });
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
